<template>
  <div class="p-2">
    <div style="margin: 20px 10px;font-weight: 600;font-size: 15px;display:flex;align-items: center;">
      单号<span style="color: #ff0000;">*</span>
      <div style="margin-left:8px;"><el-input v-model="orderNumber" placeholder="请输入单号" clearable style="width: 240px" /></div>
    </div>
    <el-card shadow="never">
      <el-table :data="assetCatalogList">
        <!-- <el-table-column label="目录编号" align="center" prop="id" v-if="routeType=='edit'" /> -->
        <!-- <el-table-column label="类型" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.type" placeholder="请选择类型" clearable>
              <el-option v-for="dict in asset_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </template>
        </el-table-column> -->

        <!-- <el-table-column label="资产名称" align="center">
          <template #default="scope">
            <el-select
              class="slese"
              id="id"
              @visible-change="handleVisibleChange"
              v-model="scope.row.name"
              placeholder="请选择资产"
              ref="selectRef"
              @change="changed($event,scope.$index)"
              :disabled="routeType=='edit'"
            >
              <el-option v-for="item in selectoptions" :key="item.id" :label="item.name" :value="item.id" />
              <p v-if="loadingmore">加载中</p>
              <p v-if="loadingnomore">无数据</p>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="类别" align="center">
          <template #default="scope">
            <el-select style="width:100%;" v-model="scope.row.category" placeholder="请选择类别" disabled>
              <el-option v-for="item in categoryData" :key="item.id" :label="item.category" :value="item.id" />
            </el-select>
          </template>
        </el-table-column> -->
        <el-table-column align="center">
          <template #header>
            <div>名称 <span style="color: #ff0000;">*</span></div>
          </template>
          <template #default="scope">
            <el-autocomplete
              class="inputInfo"
              v-model="scope.row.name"
              :fetch-suggestions="querySearch"
              placeholder="请输入内容"
              @select="handleSelect"
            ></el-autocomplete>
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template #header>
            <div>型号</div>
          </template>
          <template #default="scope">
            <el-input v-model="scope.row.model" placeholder="请输入型号" clearable />
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template #header>
            <div>单位 <span style="color: #ff0000;">*</span></div>
          </template>
          <template #default="scope">
            <el-input v-model="scope.row.unit" placeholder="请输入单位" clearable />
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template #header>
            <div>入库数量 <span style="color: #ff0000;">*</span></div>
          </template>
          <template #default="scope">
            <el-input-number style="width:100%;" v-model="scope.row.inventoryQuantity" :min="1" @change="getTotalNum(scope.row,scope.$index)" />
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template #header>
            <div>单价 <span style="color: #ff0000;">*</span></div>
          </template>
          <template #default="scope">
            <el-input-number style="width:100%;" v-model="scope.row.univalence" :min="0" @change="getTotalNum(scope.row,scope.$index)" />
          </template>
        </el-table-column>
        <el-table-column label="合计" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.total" clearable disabled />
          </template>
        </el-table-column>
        <el-table-column label="入库时间" align="center">
          <template #header>
            <div>
              入库时间 <br />
              <el-switch
                v-model="sjswitchType"
                class="ml-2"
                inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                active-text="整体一致"
                inactive-text="逐个修改"
              />
            </div>
          </template>
          <template #default="scope">
            <el-date-picker
              clearable
              v-model="scope.row.storageTime"
              value-format="YYYY-MM-DD"
              type="date"
              placeholder="请选择开始时间"
              style="width:100%;"
              class="date-picker-width"
              @change="sjchanged(scope.row)"
            >
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.remark" placeholder="请输入备注" clearable />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="routeType=='add'" width="50">
          <template #default="scope">
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="assetCatalogList = assetCatalogList.filter(item => item != scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div style="display: flex;justify-content: center;margin-top: 20px;">
      <el-button v-if="routeType == 'add'" type="primary" icon="Plus" @click="addLine" v-show="routeType=='add'">追加一条</el-button>
      <el-button type="success" icon="Position" @click="handleQuery">提交全部</el-button>
      <el-button @click="goBack">返 回</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
// 获取目录列表
import { listAssetCatalog } from '@/api/business/assetCatalog';
import { listAssetInventoryRecords, getAssetInventoryRecords, delAssetInventoryRecords, addAssetInventoryRecords, updateAssetInventoryRecords, getNameList, generateOrderAddNumber } from '@/api/business/assetInventoryRecords';
import { AssetInventoryRecordsVO, AssetInventoryRecordsQuery, AssetInventoryRecordsForm } from '@/api/business/assetInventoryRecords/types';
import { listAssetCategory } from '@/api/business/assetCategory/index';

const route = useRoute()
const assetCatalogList = ref([]);
const orderNumber = ref('');
const listItem: AssetInventoryRecordsForm = {
  id: undefined,
  type: undefined,
  orderNumber:undefined,
  // category: '',
  // name: '',
  model: "",
  unit: '',
  remark: '',
  inventoryQuantity:1,
  univalence:0,
  total:0,
  storageTime:undefined,
  remark:undefined,
}
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const routeType = ref('add');
// const treeListRef = ref<ElFormInstance>();

const queryParams = ref<ProjectQuery>({
  pageNum: 1,
  pageSize: 10,
  type:undefined
})
const total = ref(0);
// const selectmodel = ref()
const selectoptions = ref()
const loadingmore = ref(false)
const loadingnomore = ref(false)
const categoryData = ref([])
const restaurants = ref([])
const sjswitchType = ref(true);

const addLine = () => {
  if(assetCatalogList.value.length > 0) {
    sjswitchType.value?listItem.storageTime=assetCatalogList.value[0].storageTime:''
  }
  listItem.orderNumber = orderNumber.value
  assetCatalogList.value.push(JSON.parse(JSON.stringify(listItem)))
}

const deleteProperties = (objList, properties) =>{
  properties.forEach(function(property) {
    delete objList[property];
  });
}

const hasNoEmptyValues = (objArray) => {
  let flag = true
  objArray.forEach(obj => {
    deleteProperties(obj,['remark','model','orderNumber'])
    const values = Object.values(obj);
    let orderNumberCheck = orderNumber.value
    if (!values.every(value => value != null && value !== '')) {
      flag?ElMessage.error('请将信息填写完成！'):''
      flag = false
    }else if(obj.univalence == 0){
      flag?ElMessage.error('单价不为0！'):''
      flag = false
    }else if(!orderNumberCheck){
      flag?ElMessage.error('单号不能为空！'):''
      flag = false
    }else if(!obj.storageTime){
      flag?ElMessage.error('请选择入库时间！'):''
      flag = false
    }else{
      flag = true
    }
  });
  return flag
}

const handleQuery = async () => {
  assetCatalogList.value.forEach(item => {
    item.orderNumber = orderNumber.value
  })
  let checkList = JSON.parse(JSON.stringify(assetCatalogList.value))
  if (!hasNoEmptyValues(checkList)) return
  if (assetCatalogList.value[0].id) {
    try {
      await updateAssetInventoryRecords(assetCatalogList.value[0]).then(() =>  {proxy?.$modal.msgSuccess("修改成功");});
      await getNotFixedEnterInfo(assetCatalogList.value[0].id);
      await goBack()
    } catch (error) {}
  }else{
    await addAssetInventoryRecords(assetCatalogList.value).then(() =>  {proxy?.$modal.msgSuccess("新增成功");});
    await goBack()
  }
}

/** 返回 */
const goBack = () =>{
  const obj = { path: "/FixedAssetManagement/FixedAssetManagementEnterList" };
  proxy?.$tab.closeOpenPage(obj);
}

const getAssetCatalogList = async () => {
  const res = await listAssetCatalog(queryParams.value);
  selectoptions.value = res.rows
  total.value = res.total;
}

const getTotalNum = (row,index) => {
  assetCatalogList.value[index].total = (row.inventoryQuantity*row.univalence).toFixed(2)
}

// const handleVisibleChange = (visible: any) => {
//   if (visible) {
//     // 如果下拉框显示
//     let selectDropdown: any = document.querySelector('.el-select-dropdown__wrap')
//     // 监听下拉框滚动事件
//     selectDropdown.addEventListener('scroll', loadNextPage)
//   } else {
//     // 如果下拉框隐藏
//     let selectDropdown: any = document.querySelector('.el-select-dropdown__wrap')
//     // 移除下拉框滚动事件监听
//     selectDropdown.removeEventListener('scroll', loadNextPage)
//   }
// }

const loadNextPage = async () => {
  let selectDropdown: any = document.querySelector('.el-select-dropdown__wrap');
  // 判断下拉框是否触底
  if (selectDropdown.scrollTop + selectDropdown.clientHeight >= selectDropdown.scrollHeight - 2) {
    loadingnomore.value = false
    loadingmore.value = true
    if (selectoptions.value.length + 1 <= total.value && loadingmore.value) {
      queryParams.value.pageNum ++
      const res = await listAssetCatalog(queryParams.value)
      selectoptions.value.length + 1   <= total.value?selectoptions.value.push(...res.rows):''
      loadingmore.value = false
    }else{
      loadingmore.value = false
    selectDropdown.removeEventListener('scroll', loadNextPage)
    loadingnomore.value = true
    }
  } else {
    loadingnomore.value = true
  }
}

// const changed = async (id,index)=> {
//   selectoptions.value.forEach(element => {
//     if(element.id == id) {
//       assetCatalogList.value[index].category = element.category
//       assetCatalogList.value[index].name = element.name
//       assetCatalogList.value[index].model = element.model
//       assetCatalogList.value[index].unit = element.unit
//       assetCatalogList.value[index].propertyAssetCatalogId = element.id
//     }
//   });
// }

const getNotFixedEnterInfo = async (id) => {
  assetCatalogList.value = []
  const res = await getAssetInventoryRecords(id);
  assetCatalogList.value.push(JSON.parse(JSON.stringify(res.data)))
  orderNumber.value = assetCatalogList.value[0].orderNumber
}

const getCategoryData = async () =>{
  const res = await listAssetCategory();
  categoryData.value = res.rows
}

const sjchanged = async (row)=> {
  if(sjswitchType.value) {
    assetCatalogList.value.forEach(item => {
      item.storageTime = row.storageTime
    })
  }
}

/** 查询资产台账列表 */
const getList = async () => {
  // 将数组元素添加为对象的键
  let obj = {};  //创建一个临时对象
  let newData = await getNameList();
  newData.rows.forEach(item => {
    const obj = { value:item };
    restaurants.value.push(obj)
  });
}

/**名字模糊查询已有内容 */
const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? restaurants.value?.filter(createFilter(queryString))
    : restaurants.value
  // call callback function to return suggestions
  cb(results)
}
const createFilter = (queryString: string) => {
  return (name) => {
    return (
      name.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0
    )
  }
}

const handleSelect = (item) => {
  console.log(item)
}

onMounted(async () => {
  if (route.query.type) {
    routeType.value = route.query.type
  }
  await getCategoryData()
  await getAssetCatalogList()
  await getList()
  if (route.query.id) {
    await getNotFixedEnterInfo(route.query.id)
  }else{
    await generateOrderAddNumber().then(async (res) => {
      orderNumber.value = res.msg
      await addLine()
    })
  }
})
</script>
